/**
 * Project of Vehicle Routing Problem with Time Windows implements 
 * some of well-known algorithms for solving VRPTW and presents new 
 * one.
 *
 * @author Michal Drobny  
 */

package io;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import logic.algorithm.AlgorithmResult;
import logic.algorithm.AlgorithmState;
import logic.destination.Destination;
import logic.route.Cycle;

/**
 * This class represents a file writer for Algorithm Result. Contains methods useful for writing
 * files.
 * 
 * @author Michal Drobny
 * @date 6.12.2014
 */
public class AlgorithmResultWriter {

	/**
	 * Suffix for algorithm result file.
	 */
	private final static String SUFFIX = ".txt";
	
	/**
	 * Writes given Algorihm Result to file.
	 *  
	 * @param path The path
	 * @param result The result
	 */
	public static void writeAlgorithmResult(String path, String problemID, AlgorithmResult result) {
		
		if (path == null || problemID == null || result == null)
			return;
		
		try {
			File directoryPath = new File(path);
			if (!directoryPath.exists()) {
				directoryPath.mkdirs();
			}
			
			File file = new File(directoryPath, problemID + SUFFIX);
			if (!file.exists())
				file.createNewFile();
				
			PrintWriter pw = new PrintWriter(file);
			
			pw.println("Algorithm state: " + result.getAlgorithmState().toString());
			pw.println();
			
			AlgorithmState resultState = result.getAlgorithmState();
			if (resultState.equals(AlgorithmState.ONE_CYCLE_SOLUTION) || 
					resultState.equals(AlgorithmState.MORE_CYCLE_SOLUTION)) 
				for (Cycle cycle : result.getCycles()) {
					pw.print("Cycle: ");
					for (Destination destination : cycle.getDestinations())
						pw.print(destination.getName() + "\t");
					pw.println();
				}
			
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
